package com.ruoyi.framework.web.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.Address;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.pay.domain.PayCoinUserForm;
import com.ruoyi.pay.service.IPayCoinUserService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wq.domain.WqComment;
import com.ruoyi.wq.domain.WqDynamic;
import com.ruoyi.wq.domain.WqNoticeComment;
import com.ruoyi.wq.service.IWqCommentService;
import com.ruoyi.wq.service.IWqDynamicService;
import com.ruoyi.wq.service.IWqNoticeCommentService;
import com.ruoyi.wx.domain.WxMaForm;
import com.ruoyi.wx.domain.WxMpMsgForm;
import com.ruoyi.wx.service.WxMaUserService;
import com.ruoyi.wx.service.WxMsgService;
import cn.hutool.core.date.DateUtil;

@Component
public class CommentService {
	
	@Autowired
    private ISysUserService sysUserService;
	
	@Autowired
	private IWqCommentService wqCommentService;
	
	@Autowired
	private IWqDynamicService wqDynamicService;
	
	@Autowired
    private WxMsgService wxMsgService;
	
	@Autowired
	private WxMaUserService wxMaUserService;
	
	@Autowired
    private IPayCoinUserService payCoinUserService;
	
	@Autowired
	private IWqNoticeCommentService wqNoticeCommentService;

	public Boolean insertWqComment(WqComment wqComment){
		Long userId = SecurityUtils.getUserId();
    	SysUser sysUser = sysUserService.getById(userId);
    	
    	// 匹配需要消耗趣豆
		Integer coinNum = 10;
		Integer amount = payCoinUserService.getAmount();
		if(coinNum > amount){
			if(sysUser.getVipEndTime() == null || sysUser.getVipEndTime().compareTo(new Date()) < 0){
				throw new ServiceException("评论需要【"+coinNum+"】趣豆，请充值",799);
				//throw new ServiceException("评论需要【"+coinNum+"】趣豆，请充值",888);
			}else{
				coinNum = 0;
			}
		}
    	
    	Address address = AddressUtils.getAddressByIP();
    	wqComment.setUserId(sysUser.getUserId());
    	wqComment.setAvatar(sysUser.getAvatar());
    	wqComment.setNickName(sysUser.getNickName());
    	wqComment.setSex(sysUser.getSex());
    	wqComment.setPhone(sysUser.getPhonenumber());
    	String content = wqComment.getContent();
    	if(StringUtils.getMatch(content)){
    		throw new ServiceException("请文明交友，多次警告会被关进小黑屋哦");
    	}
    	
    	WxMaForm wxMaForm = new WxMaForm();
    	wxMaForm.setAppId(sysUser.getAppId());
    	wxMaForm.setMessage(content);
    	wxMaForm.setOpenId(sysUser.getOpenId());
    	Boolean checkMessage = wxMaUserService.checkMessage(wxMaForm);
    	if(!checkMessage){
    		throw new ServiceException("请文明交友，多次警告会被关进小黑屋哦");
    	}
    	
    	wqComment.setAge(sysUser.getAge());
    	wqComment.setLon(address.getLng());
    	wqComment.setLat(address.getLat());
    	wqComment.setCity(address.getCity());
    	wqCommentService.save(wqComment);
    	
    	// 更新评论数量
    	Integer commentNum = getCommentNum(wqComment.getDynamicId());
    	WqDynamic dynamic = wqDynamicService.getById(wqComment.getDynamicId());
    	dynamic.setCommentNum(commentNum);
    	wqDynamicService.updateById(dynamic);
    	
    	// 评论通知
    	if(!dynamic.getUserId().equals(userId) && "0".equals(dynamic.getIsParty())){
    		WqNoticeComment notice = new WqNoticeComment();
        	notice.setDynamicId(dynamic.getId());
        	if(StringUtils.isNotBlank(dynamic.getImage())){
        		notice.setDynamicImage(dynamic.getImage().split(",")[0]);
        	}
        	notice.setDynamicUserId(dynamic.getUserId());
        	notice.setCommentId(wqComment.getId());
        	notice.setAvatar(sysUser.getAvatar());
        	notice.setNickName(sysUser.getNickName());
        	notice.setSex(sysUser.getSex());
        	notice.setContent(wqComment.getContent());
        	notice.setNoticeUserId(dynamic.getUserId());
        	wqNoticeCommentService.save(notice);
        	
        	// 更新用户未读消息数量
        	SysUser user = sysUserService.getById(dynamic.getUserId());
        	Integer commentNewNum = wqNoticeCommentService.getUnReadNum(user.getUserId());
        	user.setCommentNewNum(commentNewNum);
        	sysUserService.updateById(user);
        	
        	// 发送微信订阅消息
            if(StringUtils.isNotBlank(user.getAppId())){
            	if(StringUtils.isNotBlank(user.getWxOpenId())){
            		WxMpMsgForm msgForm = new WxMpMsgForm();
            		msgForm.setWxId(user.getWxId());
            		msgForm.setAppId(user.getAppId());
            		msgForm.setOpenId(user.getWxOpenId());
            		Map<String,String> dataMap = new HashMap<>();
            		dataMap.put("first", "您好，您收到一条动态回复");
            		dataMap.put("keyword1", sysUser.getNickName());
            		dataMap.put("keyword2", DateUtil.now());
            		dataMap.put("keyword3", "您好，您收到一条动态回复");
            		dataMap.put("remark", "本条信息是站内信通知，祝您早日脱单！点击查看详情");
            		msgForm.setDataMap(dataMap);
            		msgForm.setPage("pages/index?index=1");
            		wxMsgService.sendTemplateMsg(msgForm);
            	}
            }
    	}
    	
    	PayCoinUserForm payCoinUserForm = new PayCoinUserForm();
		payCoinUserForm.setUserId(userId);
		payCoinUserForm.setCoinNum(coinNum);
		payCoinUserForm.setCoinType("1");
		payCoinUserForm.setSourceId(wqComment.getId());
		payCoinUserForm.setRemark("评论消费");
		payCoinUserService.savePayCoinUser(payCoinUserForm);
    	
    	return true;
	}
	
	/**
     * 获取评论数量
     * @param dynamicId
     * @return
     */
    private Integer getCommentNum(String dynamicId){
    	QueryWrapper<WqComment> qw = new QueryWrapper<>();
    	WqComment entity = new WqComment();
    	entity.setDynamicId(dynamicId);
    	qw.setEntity(entity);
    	Integer commentNum = wqCommentService.count(qw);
    	return commentNum;
    }
}
